# @Time : 2021/4/7 10:41
# @Author : Fioman 
# @Phone : 13149920693
"""
mogodb数据库的一些API,主要是封装了数据库的操作的一些API
"""
import os
import datetime
import pymongo
import threading
from tools.hd_logger import HdLogger
from tools.common_tools import get_time_now_string, get_time_now_string_for_web
from db_tools.db_data_manager import dump_data, import_data
from tools.save_image_to_device import open_database_dump_dir, open_database_import_dir
from settings import DATABASE_NAME


# from vision_process.image_operation import delete_table


def synchronized(func):
    """
    线程安全的装饰器,加一个线程锁
    :param func:
    :return:
    """
    func.__lock__ = threading.Lock()

    def lock_func(*args, **kwargs):
        with func.__lock__:
            return func(*args, **kwargs)

    return lock_func


class DbHandler(object):
    url = "mongodb://localhost:27017/"
    paramsDbName = DATABASE_NAME
    __dbHandler__ = None
    __initFlag__ = False

    @synchronized
    def __new__(cls, *args, **kwargs):
        if cls.__dbHandler__ is None:
            cls.__dbHandler__ = object.__new__(cls)
        return cls.__dbHandler__

    def __init__(self):
        if not self.__initFlag__:
            print("DbHandler.__init__() 进行初始化")
            self.__initFlag__ = True
            self.logger = HdLogger()
            self.client = pymongo.MongoClient(self.url)
            self.paramsDb = self.client[self.paramsDbName]
            # 统计所有的数据库表格
            collist = self.paramsDb.list_collection_names()

            self.orderTable = "order"
            if self.orderTable not in collist:
                data = {
                    "key": 1,
                    "cutId":0,
                    "width": 600,
                    "height": 600,
                    "lengthUnit": "mm",
                }
                self.insert_data(self.orderTable, data)

            self.mainZmcParams = "mainZmcParams"
            if self.mainZmcParams not in collist:
                data = {
                    "key": "1"
                }
                self.insert_data(self.mainZmcParams, data)

            self.workingInfoTable = "workingInfo"
            if self.workingInfoTable not in collist:
                data = {
                    "key": "1",
                    "loginSuccess": False,
                    "boardIndex": 0,
                    "cutId": 0,
                    "orderUsedKey": 1,
                    "finished": 0,
                    "timeBegin": get_time_now_string_for_web(),
                    "timeEnd": get_time_now_string_for_web(),
                    "boardThicknessMax": 100 # 放板厚度
                }
                self.insert_data(self.workingInfoTable, data)
            else:
                query = {
                    "key": "1"
                }
                newValues = {
                    "$set": {
                        "loginSuccess": False
                    }
                }
                self.update_data(self.workingInfoTable, query, newValues)

            tableName = "userinfo"
            if tableName not in collist:
                data = {
                    "id": "12",
                    "username": "user",
                    "password": "hd",
                    "role": "普通用户"
                }
                self.insert_data(tableName, data)

            self.mainAlarmInfoTable = "mainAlarmInfo"
            if self.mainAlarmInfoTable not in collist:
                data = {
                    "key": "1",
                    "mainAlarmInfo": {
                        "500": "放板机轴0报警",
                        "501": "放板机轴1报警",
                        "502": "放板机轴2报警",
                        "510": "放板机门开关故障报警",
                        "513": "放板机吸盘真空故障报警",
                        "516": "放板机门禁1报警",
                        "517": "放板机门禁2报警",
                        "518": "放板机门禁3报警",
                        "520": "放板机视觉检测故障",
                        "522": "放板机进料传感器被挡",
                        "523": "放板机拍照传感器被挡",
                        "525": "放板机进料超时",
                        "526": "放板机拍照传感器感应超时",
                        "531": "按钮急停",
                    }
                }
                self.insert_data(self.mainAlarmInfoTable, data)
            self.produceAmountRecordTable = "prodcueAmountRecord"
            if self.produceAmountRecordTable not in collist:
                data = {
                    "key": "1",
                    "recordYear": datetime.datetime.now().year,
                    "1": 0,
                    "2": 0,
                    "3": 0,
                    "4": 0,
                    "5": 0,
                    "6": 0,
                    "7": 0,
                    "8": 0,
                    "9": 0,
                    "10": 0,
                    "11": 0,
                    "12": 0,
                    "dayAmount": {

                    }
                }
                self.insert_data(self.produceAmountRecordTable, data)
            self.configParamsTable = "configParams"
            if self.configParamsTable not in collist:
                data = {
                    "key": "1",
                    "centerModuleX": 5,
                    "centerModuleY": 5,
                    "catchPosOffset": 300,
                    "angleOffset": 5,
                    "MMpix": 1,
                    "maxIndex":10000,
                    "carrierOneUpSize": 300,
                    "carrierOneDownSize": 300,
                    "carrierTwoUpSize": 300,
                    "carrierTwoDownSize": 300,
                }
                self.insert_data(self.configParamsTable,data)

            self.putBoardThicknessTable = "boardThicknessTable"
            if self.putBoardThicknessTable not in collist:
                data = {
                    "key":"1",
                    "thicknessMax1":0, # LV1的thickness表
                    "thicknessMax2":0, # LV2的thickness表
                }
                self.insert_data(self.putBoardThicknessTable, data)

            # self.camIPConnect = "camIPConnect"
            # if self.camIPConnect not in collist:
            #     data = {
            #         "key" : "1",
            #         "cutCam":{
            #             "cameraIP":"192.168.0.20",
            #             "netIP":"192.168.0.3"
            #         },
            #     }
            #     self.insert_data(self.camIPConnect,data)

    def insert_data(self, tableName, data):
        """
        传入的数据的数据类型可能是列表,如果是列表,列表里面的每一项都是字典,则认为是插入多条记录,否则就认为是插入一条记录
        :param tableName:表名
        :param data:插入的数据
        :return:
        """
        try:
            if isinstance(data, list) and len(data) > 0 and isinstance(data[0], dict):
                self.paramsDb[tableName].insert_many(data)
            elif isinstance(data, dict):
                self.paramsDb[tableName].insert_one(data)
            else:
                return "error", "in DbHandler.insert_data() 插入的数据类型错误,请传入字典,或者是字典的列表"
        except Exception as e:
            errorInfo = "in DbHandler.insert_data() error : {}".format(str(e))
            print(errorInfo)
            self.logger.debug(errorInfo)
            return "error", errorInfo
        return "ok", ""

    def update_data(self, tableName, query, newValues, updateOne=False):
        """
        更新数据,根据query筛选条件去更新数据
        :param tableName: 表名
        :param query: 筛选条件
        :param newValues: 新的值
        :param updateOne: 是否只更新一条的标志位
        :return:1. 成功返回 "ok",空串  2. 失败返回 "error","失败原因"
        """
        try:
            if updateOne:
                self.paramsDb[tableName].update_one(query, newValues)
            else:
                self.paramsDb[tableName].update_many(query, newValues)
        except Exception as e:
            errorInfo = "in DbHandler.update_data(),error : {}".format(str(e))
            print(errorInfo)
            self.logger.debug(errorInfo)
            return "error", errorInfo
        return "ok", ""

    def delete_data(self, tableName, query, deleteOne=False):
        """
        删除数据库,根据数据库的表名删除指定数据库的指定条件的内容
        :param tableName: 表名
        :param query: 删除条件
        :param deleteOne: 是否只删除一条
        :return:1.成功返回"ok"和空串 2.失败返回error,失败原因
        """
        try:
            if deleteOne:
                self.paramsDb[tableName].delete_one(query)
            else:
                self.paramsDb[tableName].delete_many(query)
        except Exception as e:
            errorInfo = "in DbHandler.delete_data(),error : {}".format(str(e))
            print(errorInfo)
            self.logger.debug(errorInfo)
            return "error", errorInfo

    def get_data_list(self, tableName, query=None, projection=None, sort="", direction=1):
        """
        根据数据库的表名,以及查询条件,获取这个数据库表中的所有的数据
        :param tableName:数据库表名
        :param query:查询条件
        :param projection:过滤条件
        :param sort:排序
        :param direction:方向
        :return: 1. 成功返回"ok",查找到的数据列表,如果查找的数据列表是空   2. 失败返回"error",以及失败原因
        """
        try:
            if query is None:
                query = {}
            if projection is None:
                projection = {
                    "_id": 0,
                    "time": 0
                }
            if sort == "":
                findData = list(self.paramsDb[tableName].find(query, projection))
            else:
                findData = list(self.paramsDb[tableName].find(query, projection).sort(sort, direction))
        except Exception as e:
            errorInfo = "in DbHandler.get_data(),error : {}".format(str(e))
            print(errorInfo)
            self.logger.debug(errorInfo)
            return "error", errorInfo
        if len(findData) == 0:
            return "error", "数据表 {} 查找到的数据是空".format(tableName)
        else:
            return "ok", findData

    def get_data_one(self, tableName, query=None, projection=None, sort="", direction=1):
        """
         根据数据库的表名,以及查询条件,获取这个数据库表中的一条数据,一般这个情况数据库中也只有唯一的一条数据
        :param tableName:数据库表名
        :param query:查询条件
        :param projection:过滤条件
        :param sort:排序
        :param direction:方向
        :return: 1. 成功返回"ok",查找到的数据列表,如果查找的数据列表是空   2. 失败返回"error",以及失败原因
        :param tableName:
        :param query:
        :param projection:
        :param sort:
        :param direction:
        :return:
        """
        try:
            if query is None:
                query = {}
            if projection is None:
                projection = {
                    "_id": 0,
                    "time": 0
                }
            if sort == "":
                findData = list(self.paramsDb[tableName].find(query, projection))
            else:
                findData = list(self.paramsDb[tableName].find(query, projection).sort(sort, direction))
        except Exception as e:
            errorInfo = "in DbHandler.get_data(),error : {}".format(str(e))
            print(errorInfo)
            self.logger.debug(errorInfo)
            return "error", errorInfo
        if len(findData) == 0:
            return "error", "数据表 {} 查找到的数据是空".format(tableName)
        else:
            return "ok", findData[0]

    def get_usernames(self):
        try:
            userinfo = self.get_data_list('userinfo')[1]
            if len(userinfo) != 0:
                usernames = []
                for i in userinfo:
                    usernames.append(i.get('username'))
                usernames.append('admin')
                return 'ok', usernames
            else:
                return 'error', ['请使用管理员账号登录，或者请联系管理员创建用户账号！']
        except Exception as e:
            return "error", str(e)

    def update_login_state(self, isLogin):
        """
        更新用户的登陆状态
        :param isLogin:是否是登陆状态.
        :return:
        """
        tableName = "workingInfo"
        query = {
            "key": "1"
        }
        newValues = {
            "$set": {
                "loginSuccess": isLogin
            }
        }
        return self.update_data(tableName, query, newValues)

    def get_login_state(self):
        """
        获取用户的登陆状态
        :return: 登陆成功返回True,失败返回False
        """
        tableName = "workingInfo"
        query = {
            "key": "1"
        }
        res, data = self.get_data_one(tableName, query)
        if res == "ok":
            return data.get("loginSuccess", False)
        else:
            errorInfo = "in DbHandler.get_login_state() error : {}".format(data)
            print(errorInfo)
            self.logger.debug(errorInfo)
            return False

    def get_main_zmc_params(self, tableName):
        """
        获取主控制器的参数列表,只获取一条数据
        :param tableName: 拍照控制器的表名
        :return:
        """
        query = {
            "key": "1"
        }
        return self.get_data_one(tableName, query)

    def web_request_get_user_info(self):
        """
        前端界面获取所有用户的账号信息
        :return:
        """
        tableName = "userinfo"
        if tableName not in self.paramsDb.list_collection_names():
            return []
        else:
            res, userInfo = self.get_data_list(tableName)
            return userInfo if res == "ok" else []

    def web_request_save_user_info(self, userInfo):
        """
        前端界面保存用户信息
        :param userInfo:
        :return:
        """
        tableName = "userinfo"
        key = userInfo['key']
        query = {
            "key": key
        }
        queryName = {
            "username": userInfo["username"]
        }
        self.delete_data(tableName, queryName)  # 删除同名的用户账号,用户名会覆盖掉
        if userInfo["username"] == "admin":
            return "保存失败,用户名不能是admin!"
        res, data = self.get_data_one(tableName, query)
        if res != "ok":
            userInfo["registerTime"] = get_time_now_string()
            return self.insert_data(tableName, userInfo)[0]
        else:
            return self.update_data(tableName, userInfo, userInfo)[0]

    def web_request_delete_user_info(self, delKey):
        """
        前端界面点击了删除用户信息的按钮,按照key值去删除
        :param delKey: 要删除的用户信息的key值
        :return:
        """
        tableName = "userinfo"
        query = {
            "key": delKey
        }
        res, info = self.delete_data(tableName, query)
        return res if res == "ok" else info

    def get_user_list_by_username(self, username):
        """
        根据用户名获取userinfo列表
        :param username: 用户名
        :return:成功返回列表,失败返回空列表
        """
        tableName = "userinfo"
        query = {
            "username": username
        }
        res, data = self.get_data_one(tableName, query)
        return data if res == "ok" else []

    def get_order_by_key(self, orderUsedKey):
        """
        根据key值,获取工单数据
        :param orderUsedKey:
        :return:
        """
        tableName = "order"
        query = {
            "key": orderUsedKey
        }
        res, orderDict = self.get_data_one(tableName, query)
        return orderDict if res == "ok" else {}

    def get_order(self):
        tableName = "order"
        query = {
            "key": 1
        }
        return self.get_data_one(tableName, query)

    def get_board_thickness(self):
        """
        获取放板厚度表.
        :return:
        """
        tableName = self.putBoardThicknessTable
        query = {
            "key":"1"
        }
        return self.get_data_one(tableName,query)


    def web_request_get_order_by_key(self, orderUsedKey):
        """
        前端界面请求刷新工单数据
        :param orderUsedKey:
        :return:
        """
        tableName = "order"
        query = {
            "key": orderUsedKey
        }
        totalOrders = self.get_total_orders()
        res, workingOrder = self.get_data_one(tableName, query)
        if res != "ok":
            workingOrder = totalOrders[0]
        return totalOrders, [workingOrder]

    def web_request_search_order(self, orderId):
        """
        前端界面请求搜索工单
        :param orderId: 搜索的工单id号
        :return:
        """
        tableName = "order"
        query = {
            "cutId": orderId
        }
        totalOrders = self.get_total_orders()
        res, searchOrder = self.get_data_list(tableName, query)
        if res != "ok":
            searchOrder = []
        return totalOrders, searchOrder

    def save_order_used_key(self, workingKey):
        """
        保存正在作业的workingKey的值
        :param workingKey: 当前正在作业的工单key值
        :return:
        """
        query = {
            "key": "1"
        }
        newValues = {
            "$set": {
                "orderUsedKey": workingKey
            }
        }
        self.update_data(self.workingInfoTable, query, newValues)

    def get_working_used_key(self):
        """
        获取当前工作的key值.
        :return:
        """
        tableName = "workingInfo"
        query = {
            "key": "1"
        }
        res, data = self.get_data_one(tableName, query)
        if res == "ok":
            workingKey = data.get("orderUsedKey", None)
            if workingKey is None:
                oneOrder = self.get_total_orders()[0]
                workingKey = oneOrder.get("key", 0)
                newValues = {
                    "$set": {
                        "orderUsedKey": workingKey
                    }
                }
                self.update_data(tableName, query, newValues)
            return workingKey

    def get_total_orders(self):
        tableName = "order"
        query = {}
        res, data = self.get_data_list(tableName, query)
        if res != "ok":
            data = {
                "key": 1,
                "width": 600,
                "height": 600,
                "unit": "mm",
            }
            self.insert_data(tableName, data.copy())
            data = [data]
        return data

    def get_working_info(self):
        """
        获取wokinginfo数据表的内容
        :return:
        """
        tableName = self.workingInfoTable
        query = {
            "key": "1"
        }
        return self.get_data_one(tableName, query)

    def get_main_alarm_info(self):
        """
        获取mainAlarminfo数据表的内容
        :return:
        """
        query = {
            "key": "1"
        }
        return self.get_data_one(self.mainAlarmInfoTable, query)

    def web_request_get_working_info(self):
        """
        前端界面获取wokinginfo数据库的数据
        :return:
        """
        res, data = self.get_working_info()
        return data if res == "ok" else {}

    # def update_order(self, key, newData):
    #     """
    #     根据key值更新工单的信息
    #     :param key 要更新的工单的key值
    #     :param newData:新的值
    #     :return:
    #     """
    #     query = {
    #         "key": key
    #     }
    #     newValues = {
    #         "$set": newData
    #     }
    #     return self.update_data(self.orderTable, query, newValues)
    def update_order(self, orderKey):

        # data = self.get_order_by_key(orderKey)
        res, data = self.get_order()
        if res != "ok":
            return "error", data
        else:
            oldamount = data.get("amount", 0)
            newamount = oldamount + 1
            query = {
                "key": orderKey
            }
            newData = {
                "amount": newamount,
            }
            newValues = {
                "$set": newData,
            }
            return self.update_data(self.orderTable, query, newValues)

    def web_request_save_order(self, newOrder):
        """
        界面上点击了保存工单.
        :param newOrder:
        :return:
        """
        # 显示的时候使用字符串,保存的时候保存的是浮点数,这个是可以的吗,可以试一下
        # 分两种情况,工单已经存在,或者工单不存在
        tableName = "order"
        newKey = newOrder["key"]
        query = {
            "key": newKey,
        }
        res, data = self.get_data_one(tableName, query)
        if res == "ok":
            newValues = {
                "$set": newOrder
            }
            self.update_data(tableName, query, newValues)
        else:
            self.insert_data(tableName, newOrder)
        # lengthFirstMove = newL2
        # lengthSecondMove = newL1 - newL2 * 2
        # mainzmc.set_work_x0_data_to_device(newX0)
        # mainzmc.set_work_data_to_device(lengthFirstMove,lengthSecondMove,newL3,newW2)
        orderList = self.web_request_get_order_by_key(newKey)
        return ["ok", orderList]

    def web_request_delete_order(self, delKey):
        """
        前端界面请求删除工单
        :param delKey: 要删除的工单key值
        :return:
        """
        tableName = "order"
        query = {
            "key": delKey
        }
        workingKey = self.get_working_used_key()
        self.delete_data(tableName, query)
        return self.web_request_get_order_by_key(workingKey)

    def save_working_info_data(self, newData):
        """
        保存workingInfo的数据
        :param newData: 新的值
        :return:
        """
        query = {
            "key": "1"
        }
        newValues = {
            "$set": newData
        }
        return self.update_data(self.workingInfoTable, query, newValues)

    def web_reqeust_save_working_info(self, newData):
        """
        前端界面点击了保存作业信息的逻辑
        :param newData: 新的数据
        :return:
        """
        return self.save_working_info_data(newData)

    def web_request_save_main_alarm_info(self, newAlarmDict):
        """
        保存报警信息,将报警信息重新保存一下.有可能是覆盖,也有可能是更改,先将原来的字典获取到.
        :return:
        """
        res, data = self.get_main_alarm_info()
        if res != "ok":
            return data
        alarmDict = data.get("mainAlarmInfo")
        alarmKey, alarmInfoText = newAlarmDict
        if alarmInfoText == "删除":
            if str(alarmKey) in alarmDict.keys():
                del alarmDict[alarmKey]
        else:
            alarmDict[str(alarmKey)] = str(alarmInfoText)
        newValues = {
            "$set": {
                "mainAlarmInfo": alarmDict
            }
        }
        query = {
            "key": "1"
        }
        res, info = self.update_data(self.mainAlarmInfoTable, query, newValues)
        if res != "ok":
            return info
        return "ok"

    def web_request_get_main_alarm_info_table(self):
        """
        界面上点击获取报警信息表的按钮
        :return:
        """
        res, data = self.get_main_alarm_info()
        if res != "ok":
            return data
        alarmDict = data.get("mainAlarmInfo")
        newAlarmTableVal = []
        tableDataIndex1 = "bitPos"
        tableDataIndex2 = "alarmText"
        alarmDictKey = alarmDict.keys()
        newAlarmKey = sorted(alarmDictKey, key=lambda x: int(x))
        newAlarmDict = {key: alarmDict[key] for key in newAlarmKey}  # 将原来的字典按照键进行排序,组合新字典返回

        for key, val in newAlarmDict.items():
            newVal = {
                "key": key,  # table空间里面的值必须要有一个key值,不然控件那里容易报错.
                tableDataIndex1: key,
                tableDataIndex2: val
            }
            newAlarmTableVal.append(newVal)
        return newAlarmTableVal

    def get_xray_params_table_data(self):
        """
        获取xrayparamsTable的数据表结果
        :return:
        """
        tableName = self.xrayparamsTable
        query = {
            "key": "1"
        }
        return self.get_data_one(tableName, query)

    def update_xray_params(self, xrayid, axisid, angle, pixel):
        """
        更新xray里面的角度和像素比
        :return:
        """
        res, data = self.get_xray_params_table_data()
        if res != "ok":
            return "error", data
        if xrayid == 1:
            if axisid == 1:
                newData = {
                    "xray01xAngle": angle,
                    "xray01xPixelThan": pixel,
                }
            elif axisid == 2:
                newData = {
                    "xray01yAngle": angle,
                    "xray01yPixelThan": pixel,
                }
        elif xrayid == 2:
            if axisid == 1:
                newData = {
                    "xray02xAngle": angle,
                    "xray02xPixelThan": pixel,
                }
            elif axisid == 2:
                newData = {
                    "xray02yAngle": angle,
                    "xray02yPixelThan": pixel,
                }
        query = {
            "key": "1"
        }
        newValues = {
            "$set": newData,
        }

        return self.update_data(self.xrayparamsTable, query, newValues)

    def get_produce_record_table_data(self):
        """
        获取produceRecordTale的数据表的结果.
        :return:
        """
        query = {
            "key": "1"
        }
        return self.get_data_one(self.produceAmountRecordTable, query)

    def update_workinfo_count_data(self):

        res, data = self.get_working_info()
        if res != "ok":
            return "error", data
        else:
            oldfinished = data.get("finished", 0)
            newfinished = oldfinished + 1
            query = {
                "key": "1"
            }
            newData = {
                "finished": newfinished,
                "timeEnd": get_time_now_string_for_web(),
            }
            newValues = {
                "$set": newData,
            }
            return self.update_data(self.workingInfoTable, query, newValues)

    def delete_table(self, tableName):
        try:
            self.paramsDb.drop_collection(tableName)
        except Exception as e:
            errorInfo = "in DbHandler.delete_table(),error: {}".format(str(e))
            print(errorInfo)
            self.logger.debug(errorInfo)
            return "error", errorInfo

    def update_produce_record(self, boardNumbers):
        """
        更新产量记录里面的值,月份和日期都要来一遍
        :param boardNumbers: 增加的板的数量.
        :return:
        """
        # 先获取produceAmount数据
        res, data = self.get_produce_record_table_data()
        if res != "ok":
            return "error", data
        nowYear = datetime.datetime.now().year
        recordYear = data.get("recordYear")
        if nowYear != recordYear:  # 如果记录的年份变了,数据就要重新清零
            self.delete_table(self.produceAmountRecordTable)
            newData = {
                "key": "1",
                "recordYear": datetime.datetime.now().year,
                "1": 0,
                "2": 0,
                "3": 0,
                "4": 0,
                "5": 0,
                "6": 0,
                "7": 0,
                "8": 0,
                "9": 0,
                "10": 0,
                "11": 0,
                "12": 0,
                "dayAmount": {

                }
            }
            self.insert_data(self.produceAmountRecordTable, newData)

            res, data = self.get_produce_record_table_data()
            if res != "ok":
                return "error", data
        monthKey = str(datetime.datetime.now().month)
        dateKey = get_time_now_string()[5:10]
        print("monthKey = {},dateKey = {}".format(monthKey, dateKey))
        oldMonthVal = data.get(monthKey, 0)
        oldDayAmountDict = data.get("dayAmount", {})
        oldDayVal = oldDayAmountDict.get(dateKey, 0)
        newMonthVal = oldMonthVal + boardNumbers
        newDateVal = oldDayVal + boardNumbers
        oldDayAmountDict[dateKey] = newDateVal

        query = {
            "key": "1"
        }
        newData = {
            monthKey: newMonthVal,
            "dayAmount": oldDayAmountDict,
        }
        newValues = {
            "$set": newData,
        }
        return self.update_data(self.produceAmountRecordTable, query, newValues)

    @staticmethod
    def web_request_dump_data_base():
        """
        界面上点击了备份数据库,进行数据库的备份工作
        :return:
        """
        return dump_data()

    @staticmethod
    def web_request_import_data_base():
        """
        界面上点击了导入数据库,进行数据库的导入工作
        :return:
        """
        return import_data()

    @staticmethod
    def web_request_open_database_dump_dir():
        """
        界面上点击了打开备份目录
        :return:
        """
        return open_database_dump_dir()

    @staticmethod
    def web_request_open_databaes_import_dir():
        """
        界面上点击了打开导入目录
        :return:
        """
        return open_database_import_dir()

    def web_request_clear_produce_amount(self):
        """
        界面上点击了数据清零,确认按钮
        :return:
        """
        # 清空数据,并且更改当前的统计时间
        newData = {
            "finished": 0,
            "timeBegin": get_time_now_string_for_web(),
            "timeEnd": get_time_now_string_for_web(),
        }
        res, info = self.save_working_info_data(newData)
        return res, info

    def test_update_workinfo_count_data(self):

        res, data = self.get_working_info()
        if res != "ok":
            return "error", data
        else:
            oldfinished = data.get("finished", 0)
            newfinished = oldfinished + 1
            query = {
                "key": "1"
            }
            newData = {
                "finished": newfinished,
                "timeEnd": get_time_now_string_for_web(),
            }
            newValues = {
                "$set": newData,
            }
            return self.update_data(self.workingInfoTable, query, newValues)

    def test_update_produce_record_table_data(self):
        data = {
            "recordYear": datetime.datetime.now().year,
            "1": 400,
            "2": 600,
            "3": 500,
            "4": 700,
            "5": 600,
            "6": 500,
            "7": 800,
            "8": 600,
            "9": 500,
            "10": 400,
            "11": 700,
            "12": 800,
            "dayAmount": {
                # "1-5":10,
                # "1_6":12,
            }
        }
        newValues = {
            "$set": data
        }
        self.update_data(self.produceAmountRecordTable, query={"key": "1"}, newValues=newValues)

    def save_config_params(self,newData):
        """
        保存设置参数
        :param newData:
        :return:
        """
        tableName = self.configParamsTable
        query = {
            "key":"1"
        }
        newValues = {
            "$set":newData
        }
        return self.update_data(tableName,query,newValues)

    # def get_cam_IP_connect(self):
    #     """
    #     获取网口网段和相机IP
    #     :return:
    #     """
    #     tableName = self.camIPConnect
    #     query = {
    #         "key": "1"
    #     }
    #     return self.get_data_one(tableName, query)
    #
    # def get_cam_IP_connect_by_camName(self):
    #     res, IP_data = self.get_cam_IP_connect()
    #     cutCam = [IP_data.get('cutCam').get('cameraIP'),IP_data.get('cutCam').get('netIP')]
    #
    #     return cutCam

if __name__ == '__main__':
    logger = None
    db = DbHandler()
    tableNameGlobal = "cbjZmcParams"
    resMain, dataGlobal = db.get_data_one(tableNameGlobal)
    db.test_update_workinfo_count_data()
    print("res = {},data = {}".format(resMain, dataGlobal))
    db2 = DbHandler()
    db3 = DbHandler()
    print(db is db2, db2 is db3)
